#include "controlFile.h"
#include <fstream>
#include <cstring>

void controlFile::readFileConfig()
{
    std::ifstream m_envFile("/tmp/CDenvHOME");
    if(m_envFile.is_open())
    {
        m_envFile>>FilePath;
        m_envFile.close();
        unlink("/tmp/CDenvHOME");
        std::cout<<"HOME:"<<FilePath<<std::endl;
        FilePath+="/.timeList";
    }
    else
    {
        std::cout<<"Can't find HOME path"<<std::endl;
        FilePath="./timeList";
    }
    std::cout<<FilePath<<std::endl;

    errno=0;
    int fileFD=open(FilePath.c_str(),O_RDONLY | O_CREAT,S_IRUSR | S_IWUSR);
    if(fileFD==-1)
    {
        std::cerr<<"config file open failed!"<<std::endl;
        std::cerr<<std::strerror(errno);
        throw -2;
    }
    timeData aa;
    int num=0;
    if(read(fileFD,&num,sizeof(num))==0)
        std::cout<<"config is empty,Please add something"<<std::endl;
    try
    {
        m_timeData.clear();
        for(int i=0;i<num;i++)
        {
           if(read(fileFD,&(aa.stringLength),sizeof(int))!=sizeof(int))
                throw 1;
            char* readstring=new char[aa.stringLength+1];
            if(read(fileFD,readstring,aa.stringLength)!=aa.stringLength)
                throw 2;
            readstring[aa.stringLength]='\0';
            aa.Title=std::string(readstring);
            if(read(fileFD,&(aa.Time),sizeof(tm))!=sizeof(tm))
                throw 3;
            if(read(fileFD,&(aa.mode),sizeof(int))!=sizeof(int))
                throw 4;
            aa.uuid=i;
            m_timeData.push_back(aa);
        }
        if(close(fileFD)==-1)
            throw std::string("file close failed");
    }
    catch(int e)
    {
        std::cerr<<"read file failed "<<e<<std::endl;
        throw -1;
    }
    catch(std::string e)
    {
        std::cerr<<e<<std::endl;
        throw -1;
    }
}

void controlFile::writeFileConfig()
{
    int fileFD=open(FilePath.c_str(),O_WRONLY | O_CREAT | O_TRUNC,S_IRUSR | S_IWUSR);
    if(fileFD==-1)
    {
        std::cerr<<"config file write failed!"<<std::endl;
        throw -1;
    }
    int ItemNum=m_timeData.size();

    try
    {
        if(write(fileFD,&ItemNum,sizeof(int))!=sizeof(int))
            throw 5;
        for(timeData i:m_timeData)
        {
            if(write(fileFD,&(i.stringLength),sizeof(int))!=sizeof(int))
                throw 1;
            if(write(fileFD,i.Title.c_str(),i.stringLength)!=i.stringLength)
                throw 2;
            if(write(fileFD,&(i.Time),sizeof(tm))!=sizeof(tm))
                throw 3;
            if(write(fileFD,&(i.mode),sizeof(int))!=sizeof(int))
                throw 4;
        }
    }
    catch(int e)
    {
        std::cerr<<"write file failed "<<e<<std::endl;
        throw -1;
    }
    
    if(close(fileFD))
    {
        std::cerr<<"close file failed"<<std::endl;
        throw -1;
    }
}